package cwnu.sapphire.com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cwnu.sapphire.com.entity.LoginResult;
import cwnu.sapphire.com.entity.User;
import cwnu.sapphire.com.mapper.UserMapper;
import cwnu.sapphire.com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> list() {
        return userMapper.selectList(null);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean save(User user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean updateById(User user) {
        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean removeById(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public void add(List<User> users) {
        List<User> validUserList = users.stream()
                .filter(user -> user.getName() != null && !user.getName().isEmpty()) // 过滤 name 为空的记录
                .collect(Collectors.toList());
        validUserList.forEach(user -> {
            String name = user.getName();
            if (name != null && name.endsWith("*")) {
                user.setName(name.substring(0, name.length() - 1));
            }
        });
        userMapper.insert(validUserList);
    }
    
    @Override
    public LoginResult login(String username, String password) {
        // 1. 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username)
                   .eq(User::getDeleteFlag, 0); // 只查询未删除的用户
        
        List<User> users = userMapper.selectList(queryWrapper);
        
        // 2. 判断用户是否存在
        if (users == null || users.isEmpty()) {
            return LoginResult.userNotFound();
        }
        
        // 3. 遍历用户列表，查找密码匹配的用户
        for (User user : users) {
            if (password.equals(user.getPassword())) {
                // 4. 登录成功，返回用户信息（密码置空）
                user.setPassword(null);
                return LoginResult.success(user);
            }
        }
        
        // 5. 没有找到匹配的密码
        return LoginResult.passwordError();
    }
}
